<template>
  <div style="padding: 10px">
    <PackageFunctionText
      v-if="query.isolate!='user'"
      :title="$t('common.naturalResources')"
      identifying="resource_space"
      :isolate="query.isolate"
      :isolate-id="query.isolate_id"
      :token="token"
      @emitPackageFunction="emitPackageFunction"
    />
    <el-tabs v-model="activeName">
      <el-tab-pane :label="$t('common.image')" name="images">
        <el-button v-loading.fullscreen.lock="fullscreenLoading" type="primary" @click="dialogUpload = true">{{ $t('common.upload') }}<i class="el-icon-upload el-icon--right" /></el-button>
        <div class="image-div">
          <el-row :gutter="10">
            <el-col v-for="item in list" :key="item.id" :span="fileSpan" class="image-div-one">
              <el-card :body-style="{ padding: '0px' }">
                <div class="image-one" :title="$t('common.select')" @click="onResourcesSelect(item)">
                  <!--                <img :src="item.name_url" class="image" :preview-src-list="srcList">-->
                  <el-image
                    :src="item.name_url+'?x-oss-process=image/resize,w_300'"
                    style="height: 200px"
                    fit="cover"
                  />
                </div>
                <div style="padding: 14px;">
                  <div class="bottom clearfix">
                    <el-button-group class="button-group">
                      <el-button type="primary" size="mini" icon="el-icon-view" plain @click="onImageView(item)">{{ $t('common.preview') }}</el-button>
                      <el-button size="mini" icon="el-icon-delete" plain @click="onImageDelete(item)">{{ $t('common.remove') }}</el-button>
                    </el-button-group>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!--          <div v-for="item in list" :key="item.id" class="image-div-one" style="padding: 10px">-->
          <!--            <el-card :body-style="{ padding: '0px' }">-->
          <!--              <div class="image-one" :title="$t('common.select')" @click="onResourcesSelect(item)">-->
          <!--                &lt;!&ndash;                <img :src="item.name_url" class="image" :preview-src-list="srcList">&ndash;&gt;-->
          <!--                <el-image-->
          <!--                  :src="item.name_url+'?x-oss-process=image/resize,w_200'"-->
          <!--                  style="max-height: 200px"-->
          <!--                />-->
          <!--              </div>-->
          <!--              <div style="padding: 14px;">-->
          <!--                <div class="bottom clearfix">-->
          <!--                  <el-button-group>-->
          <!--                    <el-button type="primary" size="mini" icon="el-icon-view" plain @click="onImageView(item)">{{ $t('common.preview') }}</el-button>-->
          <!--                    <el-button size="mini" icon="el-icon-delete" plain @click="onImageDelete(item)">{{ $t('common.remove') }}</el-button>-->
          <!--                  </el-button-group>-->
          <!--                </div>-->
          <!--              </div>-->
          <!--            </el-card>-->
          <!--          </div>-->
        </div>

      </el-tab-pane>
      <!--      <el-tab-pane label="其他" name="other">其他</el-tab-pane>-->
    </el-tabs>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" :page-sizes="[24, 50, 100, 200]" @pagination="onList" />

    <el-dialog :title="$t('common.uploadFiles')" width="80%" :visible.sync="dialogUpload" @close="closeDialog">
      <div style="padding-bottom: 20px">
        <el-upload
          ref="upload"
          class="upload-demo"
          :action="action"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :on-error="handleError"
          :file-list="fileList"
          :headers="headers"
          :data="data"
          accept="jpg,png"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary" :disabled="submitDisabled">{{ $t('common.selectFile') }}</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" :disabled="submitDisabled" @click="submitUpload">{{ $t('common.uploadToServer') }}</el-button>
          <div slot="tip" class="el-upload__tip">{{ $t('common.uploadRestrictionReminder') }}</div>
        </el-upload>
      </div>

    </el-dialog>
    <el-dialog :visible.sync="dialogView" width="95%" style="text-align: center;" custom-class="dialog-view">
      <el-image
        :src="viewUrl"
        fit="fill"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getList, deleteResource } from '@/api/resource'
import PackageFunctionText from '@/components/PackageFunctionText'
import { getLanguage, setLanguage } from '@/utils/cookies'
import Pagination from '@/components/Pagination'

export default {
  name: 'ResourceCenter',
  components: { PackageFunctionText, Pagination },
  data() {
    return {
      activeName: 'images',
      dialogUpload: false,
      dialogView: false,
      viewUrl: '',
      fileList: [],
      action: process.env.VUE_APP_API + '/resource',
      headers: null,
      data: null,
      query: null,
      list: [],
      total: 0,
      fileType: 'image',
      listQuery: {
        page: 1,
        per_page: 24
      },
      fullscreenLoading: false,
      submitDisabled: false,
      token: '',
      fileSpan: 4
    }
  },
  created() {
    this.handleResize()
    window.addEventListener('resize', this.handleResize)

    const query = this.$route.query
    this.query = query
    this.action = this.action + '?lang=' + this.getLang()
    this.headers = {
      'Authorization': 'Bearer ' + query?.token,
      'X-Requested-With': 'XMLHttpRequest'
    }
    this.data = {
      isolate: query?.isolate,
      isolate_id: query?.isolate_id
    }
    this.token = query?.token
    this.onList()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize) // 移除事件监听器
  },
  methods: {
    handleResize() {
      const { body } = document
      const rect = body.getBoundingClientRect()
      if (rect.width <= 660) {
        this.fileSpan = 12
      } else if (rect.width <= 935) {
        this.fileSpan = 6
      } else {
        this.fileSpan = 4
      }
    },
    getLang() {
      const query = this.$route.query
      if (query?.lang) {
        setLanguage(query?.lang)
      }
      return query?.lang ?? getLanguage()
    },
    onList() {
      this.fullscreenLoading = true
      const query = this.query
      getList({
        isolate: query?.isolate,
        isolate_id: query?.isolate_id,
        lang: this.getLang(),
        page: this.listQuery.page,
        per_page: this.listQuery.per_page
      }, query?.token).then(res => {
        this.list = res.data
        this.total = res.total
        this.fullscreenLoading = false
      })
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleSuccess(response, file, fileList) {
      this.$message({
        message: '文件上传成功！',
        type: 'success',
        duration: 1 * 1000
      })
      this.fileList = []
      this.dialogUpload = false
      this.onList()
    },
    handleError(err, file, fileList) {
      err = err.toString()
      const str = err.split('Error: ').join('')
      const errJson = JSON.parse(str)

      this.$message({
        message: errJson.message,
        type: 'error',
        duration: 2 * 1000
      })
    },
    closeDialog() {
      this.onList()
    },
    onImageView(item) {
      this.dialogView = true
      this.viewUrl = item.name_url
    },
    onImageDelete(item) {
      var _this = this
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'

            deleteResource(item.id, {
              isolate: _this.query?.isolate,
              isolate_id: _this.query?.isolate_id,
              lang: this.getLang()
            }, _this.query.token).then(res => {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1 * 1000
              })

              done()
              instance.confirmButtonLoading = false

              _this.onList()
            })
          } else {
            done()
          }
        }
      })
    },
    onResourcesSelect(item) {
      window.parent.postMessage({
        type: this.fileType,
        url: item.url,
        name_url: item.name_url
      }, '*')
    },
    emitPackageFunction(data) {
      if (data.extend.quantity <= data.identifying_count) {
        this.submitDisabled = true
      }
      if (data.current_package.is_expired) {
        this.submitDisabled = true
      }
    }
  }
}
</script>
<style>
  .image-div .image-div-one{
    //float: left;
  }
  .image-one{
    border: 2px solid #ccc;
    cursor: pointer;
    height: 210px;
    width: 100%;
    text-align: center;
  }
  .image-one:hover{
    border: 2px solid #333;
  }
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
    width: 100%;
  }
  .button-group{
    width: 100%;
  }
  .button-group button {
    width: 50%;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }
  .dialog-view{
    margin-top: 1% !important;
    background: rgba(0, 0, 0, 0.1);
  }
</style>
